package com.ygswglxt.leave.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ygswglxt.leave.entity.LeaveBalance;
import com.ygswglxt.leave.entity.LeaveBalanceLog;
import com.ygswglxt.leave.mapper.LeaveBalanceMapper;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class LeaveBalanceService {
    
    @Autowired
    private LeaveBalanceMapper leaveBalanceMapper;
    
    /**
     * 获取所有员工的假期余额（HR使用）
     */
    public Result<List<LeaveBalance>> getAllBalances() {
        List<LeaveBalance> balances = leaveBalanceMapper.selectAllWithUserName();
        return Result.success(balances);
    }
    
    /**
     * 获取指定员工的假期余额
     */
    public Result<LeaveBalance> getBalanceByUserId(Long userId) {
        LeaveBalance balance = leaveBalanceMapper.selectByUserIdWithUserName(userId);
        if (balance == null) {
            // 如果不存在，创建默认余额记录
            balance = createDefaultBalance(userId);
        }
        return Result.success(balance);
    }
    
    /**
     * 创建默认余额记录
     */
    private LeaveBalance createDefaultBalance(Long userId) {
        LeaveBalance balance = new LeaveBalance();
        balance.setUserId(userId);
        balance.setAnnualBalance(BigDecimal.ZERO);
        balance.setSickBalance(BigDecimal.ZERO);
        balance.setPersonalBalance(BigDecimal.ZERO);
        balance.setAdjustmentBalance(BigDecimal.ZERO);
        balance.setCreateTime(new Date());
        balance.setUpdateTime(new Date());
        leaveBalanceMapper.insert(balance);
        return leaveBalanceMapper.selectByUserIdWithUserName(userId);
    }
    
    /**
     * 设置或更新员工的假期余额（HR使用）
     */
    @Transactional
    public Result<String> updateBalance(Long userId, BigDecimal annualBalance, BigDecimal sickBalance,
                                        BigDecimal personalBalance, BigDecimal adjustmentBalance, 
                                        String reason, Long operatorId) {
        LeaveBalance balance = leaveBalanceMapper.selectOne(new QueryWrapper<LeaveBalance>().eq("user_id", userId));
        
        if (balance == null) {
            // 创建新记录
            balance = new LeaveBalance();
            balance.setUserId(userId);
            balance.setAnnualBalance(annualBalance != null ? annualBalance : BigDecimal.ZERO);
            balance.setSickBalance(sickBalance != null ? sickBalance : BigDecimal.ZERO);
            balance.setPersonalBalance(personalBalance != null ? personalBalance : BigDecimal.ZERO);
            balance.setAdjustmentBalance(adjustmentBalance != null ? adjustmentBalance : BigDecimal.ZERO);
            balance.setCreateTime(new Date());
            balance.setUpdateTime(new Date());
            leaveBalanceMapper.insert(balance);
        } else {
            // 更新记录
            UpdateWrapper<LeaveBalance> wrapper = new UpdateWrapper<>();
            wrapper.eq("user_id", userId);
            if (annualBalance != null) {
                wrapper.set("annual_balance", annualBalance);
            }
            if (sickBalance != null) {
                wrapper.set("sick_balance", sickBalance);
            }
            if (personalBalance != null) {
                wrapper.set("personal_balance", personalBalance);
            }
            if (adjustmentBalance != null) {
                wrapper.set("adjustment_balance", adjustmentBalance);
            }
            wrapper.set("update_time", new Date());
            leaveBalanceMapper.update(null, wrapper);
        }
        
        return Result.success("假期余额更新成功");
    }
    
    /**
     * 扣除假期余额（审批通过时调用）
     */
    @Transactional
    public Result<String> deductBalance(Long userId, String leaveType, BigDecimal days, Long leaveId, String reason) {
        LeaveBalance balance = leaveBalanceMapper.selectOne(new QueryWrapper<LeaveBalance>().eq("user_id", userId));
        
        if (balance == null) {
            balance = createDefaultBalance(userId);
        }
        
        BigDecimal balanceBefore = BigDecimal.ZERO;
        BigDecimal balanceAfter = BigDecimal.ZERO;
        String balanceField = "";
        
        // 根据请假类型确定要扣除的余额字段
        switch (leaveType) {
            case "ANNUAL":
                balanceBefore = balance.getAnnualBalance();
                balanceAfter = balanceBefore.subtract(days);
                if (balanceAfter.compareTo(BigDecimal.ZERO) < 0) {
                    return Result.error("年假余额不足");
                }
                balance.setAnnualBalance(balanceAfter);
                balanceField = "annual_balance";
                break;
            case "SICK":
                balanceBefore = balance.getSickBalance();
                balanceAfter = balanceBefore.subtract(days);
                if (balanceAfter.compareTo(BigDecimal.ZERO) < 0) {
                    return Result.error("病假余额不足");
                }
                balance.setSickBalance(balanceAfter);
                balanceField = "sick_balance";
                break;
            case "PERSONAL":
                balanceBefore = balance.getPersonalBalance();
                balanceAfter = balanceBefore.subtract(days);
                if (balanceAfter.compareTo(BigDecimal.ZERO) < 0) {
                    return Result.error("事假余额不足");
                }
                balance.setPersonalBalance(balanceAfter);
                balanceField = "personal_balance";
                break;
            case "ADJUSTMENT":
                balanceBefore = balance.getAdjustmentBalance();
                balanceAfter = balanceBefore.subtract(days);
                if (balanceAfter.compareTo(BigDecimal.ZERO) < 0) {
                    return Result.error("调休余额不足");
                }
                balance.setAdjustmentBalance(balanceAfter);
                balanceField = "adjustment_balance";
                break;
            default:
                return Result.error("未知的请假类型");
        }
        
        // 更新余额
        UpdateWrapper<LeaveBalance> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.set(balanceField, balanceAfter);
        wrapper.set("update_time", new Date());
        leaveBalanceMapper.update(null, wrapper);
        
        return Result.success("余额扣除成功");
    }
    
    /**
     * 增加假期余额
     */
    @Transactional
    public Result<String> increaseBalance(Long userId, String leaveType, BigDecimal days, String reason, Long operatorId) {
        LeaveBalance balance = leaveBalanceMapper.selectOne(new QueryWrapper<LeaveBalance>().eq("user_id", userId));
        
        if (balance == null) {
            balance = createDefaultBalance(userId);
        }
        
        BigDecimal balanceBefore = BigDecimal.ZERO;
        BigDecimal balanceAfter = BigDecimal.ZERO;
        String balanceField = "";
        
        // 根据请假类型确定要增加的余额字段
        switch (leaveType) {
            case "ANNUAL":
                balanceBefore = balance.getAnnualBalance();
                balanceAfter = balanceBefore.add(days);
                balance.setAnnualBalance(balanceAfter);
                balanceField = "annual_balance";
                break;
            case "SICK":
                balanceBefore = balance.getSickBalance();
                balanceAfter = balanceBefore.add(days);
                balance.setSickBalance(balanceAfter);
                balanceField = "sick_balance";
                break;
            case "PERSONAL":
                balanceBefore = balance.getPersonalBalance();
                balanceAfter = balanceBefore.add(days);
                balance.setPersonalBalance(balanceAfter);
                balanceField = "personal_balance";
                break;
            case "ADJUSTMENT":
                balanceBefore = balance.getAdjustmentBalance();
                balanceAfter = balanceBefore.add(days);
                balance.setAdjustmentBalance(balanceAfter);
                balanceField = "adjustment_balance";
                break;
            default:
                return Result.error("未知的请假类型");
        }
        
        // 更新余额
        UpdateWrapper<LeaveBalance> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.set(balanceField, balanceAfter);
        wrapper.set("update_time", new Date());
        leaveBalanceMapper.update(null, wrapper);
        
        return Result.success("余额增加成功");
    }
}

